import Https from "@/utils/Https";
import { PageContainer } from "@ant-design/pro-components";
import { FC, useEffect, useRef, useState } from "react";
import { connect, history, useParams } from "umi";
import {
  Cascader,
  Form,
  Input,
  InputNumber,
  Spin,
  Image,
  Card,
  Select,
  Space,
  Button,
  message,
} from "antd";
import EditTable from "./EditTable";
import UploadPreview from "@/components/UploadPreview";
import styles from "./styles.less";
import { DeleteOutlined } from "@ant-design/icons";
import { namespace } from "./configFile";
import MapContainer from "@/components/MapContainer";
import { getItem } from "@/utils/localstorage";
const VenueDetails: FC<any> = (props) => {
  const { dispatch, arrRegion, allLabel } = props;
  const { id } = useParams();
  const [form] = Form.useForm();
  const tableRef = useRef(null);
  const [loading, setLoading] = useState(false);
  const [wechatUrl, setWechatUrl] = useState("");
  const [locationName, setLocationName] = useState("");
  const [lnglat, setLnglat] = useState(["", ""]);
  const [venueImgList, setVenueImgList] = useState([]);
  const [defaultCity, setDefaultCity] = useState("");
  const [venueMapTitle, setVenueMapTitle] = useState("");
  const WeeksData = [
    { label: "周一", value: "1" },
    { label: "周二", value: "2" },
    { label: "周三", value: "3" },
    { label: "周四", value: "4" },
    { label: "周五", value: "5" },
    { label: "周六", value: "6" },
    { label: "周日", value: "7" },
  ];
  const getDetails = async (venueId) => {
    setLoading(true);
    let res: any = await Https.get(
      "/venue/info/venueDetail",
      { id: venueId ? venueId : getItem("venueInfo").id },
      true
    );
    setLoading(false);
    if (res.code == 200) {
      setWechatUrl(res.data.wechatQrCode);
      setVenueImgList(
        res.data.venueHeadPicUrl ? res.data.venueHeadPicUrl.split(",") : []
      );
      form.setFieldsValue({
        ...res.data,
        region: res.data.region ? res.data.region.split("-") : [],
        venueFacility: res.data.venueFacility
          ? res.data.venueFacility.split(",")
          : [],
      });
      setDefaultCity(res.data.region.split("-")[1]);
      let longitude = res.data.longitude ? res.data.longitude : "";
      let latitude = res.data.latitude ? res.data.latitude : "";
      setLnglat([longitude, latitude]);
      setLocationName(res.data.locationName);
      setVenueMapTitle(res.data.venueMapTitle);
      if (res.data.venueTradeHours) {
        let venueTradeHours = JSON.parse(res.data.venueTradeHours);
        if (venueTradeHours.length) {
          venueTradeHours = venueTradeHours.map((trad) => {
            return {
              ...trad,
              days: trad.days
                .split(",")
                .map((day) => {
                  let weekData = WeeksData.filter((week) => week.value === day);
                  return weekData.length ? weekData[0].label : "";
                })
                .join(","),
              time: Array.isArray(trad.time) ? trad.time : trad.time.split("-"),
            };
          });
          tableRef.current?.setDataSource(venueTradeHours);
          tableRef.current?.setEditableRowKeys(
            venueTradeHours.map((trad) => trad.id)
          );
        }
      }
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    dispatch({
      type: `${namespace}/pageInit`,
    });
    if (id != "0") {
      getDetails(id);
    }
  }, [id]);
  //提交
  const saveOrder = async () => {
    await tableRef.current.editForm.validateFields();
    let dataSource = [...tableRef.current.dataSource];
    dataSource = dataSource.map((data) => {
      return {
        ...data,
        days: data.days
          .split(",")
          .map((day) => {
            let weekData = WeeksData.filter((week) => week.label === day);
            return weekData.length ? weekData[0].value : "";
          })
          .join(","),
        time: data.time.join("-"),
      };
    });
    form.setFieldValue("venueTradeHours", JSON.stringify(dataSource));
    const res = await form.validateFields();
    if (!tableRef.current.dataSource.length) {
      message.warning("营业时间不能为空");
      return false;
    }
    let params = {
      ...res,
      venueHeadPicUrl: venueImgList.length > 0 ? venueImgList.toString() : "",
      wechatQrCode: res.wechatQrCode ? res.wechatQrCode : "",
      venueFacility:
        res.venueFacility && res.venueFacility.length > 0
          ? res.venueFacility.join()
          : "",
      region: res.region.join("-"),
      longitude: lnglat[0],
      latitude: lnglat[1],
      locationName,
      venueMapTitle,
    };
    let result;
    setLoading(true);
    if (getItem("venueInfo").id) {
      result = await Https.post(
        "/venue/info/updateVenue",
        { ...params, id: getItem("venueInfo").id },
        true
      );
      setLoading(false);
    } else {
      if (id != "0") {
        result = await Https.post(
          "/venue/info/updateVenue",
          { ...params, id },
          true
        );
      } else {
        result = await Https.post("/venue/info/addVenue", params, true);
      }
      setLoading(false);
    }
    if (result.code == 200) {
      message.success("保存成功");
      if (!getItem("venueInfo").id) {
        history.push("/brand/information", { type: "1" });
      }
    } else {
      message.error(result.msg);
    }
  };
  return (
    <Spin spinning={loading}>
      <PageContainer
        title={id != "0" ? "编辑场馆" : "新增场馆"}
        onBack={() => {
          getItem("venueInfo").id
            ? ""
            : history.push("/brand/information", { type: "1" });
        }}
        className={[
          styles.venueDetail,
          getItem("venueInfo").id ? styles.hiddenBack : "",
        ].join(" ")}
        footer={[
          <Space key="Space">
            {!getItem("venueInfo").id && (
              <Button
                key="cancel"
                onClick={() => {
                  history.push("/brand/information", { type: "1" });
                }}
                size="large"
              >
                取消
              </Button>
            )}
            <Button
              type="primary"
              size="large"
              key="save"
              style={{ marginLeft: "20px" }}
              loading={loading}
              onClick={() => {
                saveOrder();
              }}
            >
              提交
            </Button>
          </Space>,
        ]}
      >
        <Form form={form} layout="vertical">
          <Card title="基础信息">
            <Form.Item
              label="场馆名称"
              name="venueName"
              rules={[{ required: true, message: "场馆名称不能为空" }]}
            >
              <Input maxLength={20} placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="联系人"
              name="contacts"
              rules={[{ required: true, message: "联系人不能为空" }]}
            >
              <Input maxLength={20} placeholder="请输入" />
            </Form.Item>
            <Form.Item
              label="联系电话"
              name="contactsPhone"
              rules={[
                { required: true, message: "联系电话不能为空" },
                {
                  pattern:
                    /^1(3[0-9]|4[01456879]|5[0-3,5-9]|6[2567]|7[0-8]|8[0-9]|9[0-3,5-9])\d{8}$/,
                  message: "请输入正确的手机号",
                },
              ]}
            >
              <InputNumber
                style={{ width: "100%" }}
                maxLength={11}
                placeholder="请输入"
              />
            </Form.Item>
            <Form.Item label="场馆设施" name="venueFacility">
              <Select
                mode="multiple"
                allowClear
                style={{ width: "100%" }}
                placeholder="请选择"
              >
                {allLabel.map((v) => (
                  <Select.Option value={v.id}>{v.facilityName}</Select.Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item label="微信号" name="contactsWechat">
              <Input maxLength={20} placeholder="请输入" />
            </Form.Item>
            <br />
            <Form.Item
              label="微信二维码"
              name="wechatQrCode"
              extra="图片支持jpg/png格式"
            >
              {wechatUrl ? (
                <div className={styles.avatar_wecha}>
                  <Image width={100} src={wechatUrl} />
                  <a
                    onClick={() => {
                      form.setFieldsValue({ wechatQrCode: "" });
                      setWechatUrl("");
                    }}
                  >
                    <DeleteOutlined
                      style={{ fontSize: "15px", color: "#ffffff" }}
                    />
                  </a>
                </div>
              ) : (
                <UploadPreview
                  onSuccess={(e) => {
                    form.setFieldsValue({ wechatQrCode: e });
                    setWechatUrl(e);
                  }}
                />
              )}
            </Form.Item>
            <Form.Item
              label="场馆头图"
              name="venueHeadPicUrl"
              extra="图片支持jpg/png格式,最多上传5张"
              style={{ width: "60%" }}
            >
              <div className={styles.upload_box}>
                {venueImgList.length > 0 && (
                  <div className={styles.avatar_box}>
                    {venueImgList.map((item, index) => (
                      <div className={styles.avatar_item} key={index}>
                        <Image width={140} height={100} src={item} />
                        <a
                          onClick={() => {
                            let objList = [...venueImgList];
                            objList.splice(index, 1);
                            form.setFieldsValue({
                              venueHeadPicUrl: objList,
                            });
                            setVenueImgList(objList);
                          }}
                        >
                          <DeleteOutlined
                            style={{ fontSize: "15px", color: "#ffffff" }}
                          />
                        </a>
                      </div>
                    ))}
                  </div>
                )}
                {venueImgList.length < 5 && (
                  <UploadPreview
                    aspect={1.4}
                    onSuccess={(e) => {
                      let objList = [...venueImgList];
                      objList.push(e);
                      form.setFieldsValue({ venueHeadPicUrl: objList });
                      setVenueImgList(objList);
                    }}
                  />
                )}
              </div>
            </Form.Item>
          </Card>
          <Card title="地址选择">
            <Form.Item
              label="省市区选择"
              name="region"
              rules={[{ required: true, message: "省市区不能为空" }]}
            >
              <Cascader
                options={arrRegion}
                onChange={(e) => {
                  setDefaultCity(e[1]);
                  setLocationName(e[1] + "人民政府");
                  setLnglat(["", ""]);
                  form.setFieldsValue({ venueAddress: "" });
                }}
                fieldNames={{
                  label: "label",
                  value: "label",
                }}
              />
            </Form.Item>
            <div
              style={{
                margin: "24px 0",
                width: "100%",
                height: "500px",
                position: "relative",
              }}
            >
              <MapContainer
                onSuccess={(params) => {
                  setLocationName(params.locationName);
                  setVenueMapTitle(params.locationName);
                  setLnglat(params.Lnglat);
                  form.setFieldsValue({ venueAddress: params.location });
                }}
                venueMapTitle={venueMapTitle}
                searchAddress={locationName}
                defaultValue={lnglat}
                defaultCity={defaultCity}
              />
            </div>
            <Form.Item
              label="详细地址"
              name="venueAddress"
              rules={[{ required: true, message: "详细地址不能为空" }]}
              style={{ width: "100%" }}
            >
              <Input placeholder="请输入" disabled />
            </Form.Item>
          </Card>
          <Card title="营业设置">
            <Form.Item
              label="营业时间"
              name="venueTradeHours"
              style={{ width: "100%" }}
              rules={[{ required: true, message: "营业时间不能为空" }]}
            >
              <EditTable ref={tableRef}></EditTable>
            </Form.Item>
          </Card>
        </Form>
      </PageContainer>
    </Spin>
  );
};
export default connect((state) => ({
  ...state[namespace],
  submitLoading: state.loading.effects[`${namespace}/submitItem`],
}))(VenueDetails);
